package fr.afcepf.iziticket.services;

import java.util.Date;
import java.util.List;

import fr.afcepf.iziticket.beans.MainManagedBean;
import fr.afcepf.iziticket.dao.interfaces.DAOCommande;
import fr.afcepf.iziticket.dao.interfaces.DAOReservation;
import fr.afcepf.iziticket.dao.interfaces.DAOSeance;
import fr.afcepf.iziticket.entities.Commande;
import fr.afcepf.iziticket.entities.Reservation;
import fr.afcepf.iziticket.entities.Seance;
import fr.afcepf.iziticket.entities.Utilisateur;
import fr.afcepf.iziticket.entityviews.ReservationVue;

public class PanierService {

	private static PanierService service;
	
	public static PanierService getService(){
		if(service==null)
			service = new PanierService();
		return service;
	}
	
	private PanierService() {
	}
	
	public ReservationVue getSeance(int idSeance, int quantite) {

		DAOSeance daoS = (DAOSeance) MainManagedBean.getContext().getBean("daoSeance");
		Seance seance = daoS.get(idSeance);

		Reservation reservation = new Reservation();
		reservation.setSeance(seance);

		float tva = seance.getSpectacle().getTva().getValeurTva()* seance.getSpectacle().getPuht();
		reservation.setTva(tva);
		reservation.setPuht(seance.getSpectacle().getPuht());
		reservation.setQuantite(quantite);

		ReservationVue reservVue = new ReservationVue();
		reservVue.setReservation(reservation);
		return reservVue;
	}

	public boolean valider(Utilisateur utilisateur,	List<ReservationVue> reservationsVues) {

		if (utilisateur != null) {

			DAOCommande daoC = (DAOCommande) MainManagedBean.getContext().getBean("daoCommande");
			DAOReservation daoR = (DAOReservation) MainManagedBean.getContext().getBean("daoReservation");
			DAOSeance daoS = (DAOSeance) MainManagedBean.getContext().getBean("daoSeance");

			Commande commande = new Commande();
			commande.setDateCommande(new Date());
			commande.setUtilisateur(utilisateur);

			for (ReservationVue resVue : reservationsVues) {
				commande.getReservations().add(resVue.getReservation());
				resVue.getReservation().setCommande(commande);
			}

			daoC.save(commande);
			
			for (ReservationVue resv : reservationsVues) {
				
				Seance seance = resv.getReservation().getSeance();
				int placeTotal = seance.getSpectacle().getNombrePlaces();
				
				if(resv.getReservation().getQuantite()<=(placeTotal-resv.getReservation().getQuantite())){
					daoR.save(resv.getReservation());
					seance.setPlacesVendues(seance.getPlacesVendues()+resv.getReservation().getQuantite());
					daoS.save(seance);
				}
			}
			return true;
		}
		else{
			return false;
		}
	}
}
